/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode empty;
        empty.next = head;
        ListNode *back = &empty;
        ListNode *cur = head;
        if (cur==nullptr||cur->next==nullptr) return head;
        while(cur->next!=nullptr){
            if (cur->next->val==cur->val){
                int x = cur->val;
                while(cur->next!=nullptr){
                    if (cur->val==x){
                        ListNode *temp = cur;
                        cur = cur->next;
                        delete temp;
                    }else{
                        back->next = cur;
                        break;
                    }
                }
                if (cur->next==nullptr){
                    if (cur->val==x){
                        back->next=nullptr;
                        break;
                    }else{
                        back->next=cur;
                        break;
                    }
                }
            }else{
                cur = cur->next;
                back = back->next;
            }
        }
        return empty.next;
    }
};